# -*- coding: utf-8 -*-

from odoo import api, fields, models, _


class SaleOrder(models.Model):
    _inherit = 'sale.order'

    def add_order_line(self):
        self.ensure_one()
        context = {
            'parent_model': self._name,
            'parent_id': self.id,
        }

        return {
            'type': 'ir.actions.act_window',
            'model': 'ir.actions.act_window',
            'name': _('ADD Order Lines'),
            'res_model': 'sale.order.wizard',
            'view_type': 'form',
            'view_mode': 'form',
            "view_id": False,
            'target': 'new',
            'context': context
        }


class SaleOrderWizard(models.TransientModel):
    _name = 'sale.order.wizard'
    _description = 'Sale Order Wizard'

    product_id = fields.Many2one('product.template', string='product', required=True, index=True)
    qty = fields.Float(string='quantity', default=0, required=True)
    price = fields.Float(string='Price', default=0.0, required=True)
    uom_id = fields.Many2one('uom.uom', string="uom", store=True, readonly=True, related='product_id.uom_id')

    def do_confirm(self):
        model_name = self._context.get('parent_model', False)
        model_id = self._context.get('parent_id', False)
        taking_id = self.env[model_name].search([('id', '=', model_id)])
        taking_id.order_line = [(0, 0, {
            'name': self.product_id.name,
            'product_template_id': self.product_id.id,
            'product_id': self.product_id.product_variant_id.id,
            'product_uom_qty': self.qty,
            'price_unit': self.price,
            'product_uom': self.uom_id.id,
        })]
